package com.gamelife.web.service;

import com.gamelife.web.config.redis.RedisCache;
import com.gamelife.web.constant.CacheConstants;
import com.gamelife.web.constant.Constants;
import com.gamelife.web.domain.LoginUser;
import com.gamelife.web.exception.ServiceException;
import com.gamelife.web.exception.login.CaptchaErrorException;
import com.gamelife.web.exception.login.CaptchaExpireException;
import com.gamelife.web.exception.login.UserPasswordNotMatchException;
import com.gamelife.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
public class SysLoginService {

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private RedisCache redisCache;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid) {

        // 验证码校验
        validateCaptcha(code, uuid);

        // 用户验证
        Authentication authentication = null;


        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (RuntimeException e) {
            if (e instanceof BadCredentialsException) {
                throw new UserPasswordNotMatchException();
            } else {
                throw new ServiceException(e.getMessage());
            }
        }


        // 获取当前用户
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String token = JwtUtils.createToken(loginUser.getSysUser().getId());

        // 存入redis
        redisCache.setCacheObject(Constants.LOGIN_USER_KEY + loginUser.getSysUser().getId(), loginUser);

        // 生成token
        return token;
    }

    /**
     * 校验验证码
     *
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String code, String uuid) {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null) {
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha)) {
            throw new CaptchaErrorException();
        }
    }
}
